//
//  XPhotoModel.m
//  XPhotoLibraryKit
//
//  Created by Wu,Xinting on 2018/3/20.
//

#import "XPhotoModel.h"
#import "XPhoto.h"

static NSString *SavedPhotoName = @"CheckedPhotos";
@interface XPhotoModel ()

@property (nonatomic, strong) PHFetchResult<PHAssetCollection *> *collections;
@property (nonatomic, strong) NSMutableDictionary<PHAssetCollection *, NSMutableArray<XPhoto *> *> * collAssets;

@end

@implementation XPhotoModel

- (instancetype)init {
    if (self = [super init]) {

    }
    return self;
}

- (void)loadPhotos {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"startDate" ascending:NO];
    options.sortDescriptors = @[descriptor];
    self.collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeMoment subtype:PHAssetCollectionSubtypeAny options:options];
    [self.collections enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(PHAssetCollection * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self loadAssets:obj];
    }];
}

- (void)saveChecked:(void (^)(void))doneBlock {
    NSMutableArray<XPhoto *> *savePhotos = [NSMutableArray array];
    for (NSArray<XPhoto *> *photos in self.collAssets.allValues) {
        [photos enumerateObjectsUsingBlock:^(XPhoto * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.checked) {
                obj.checked = NO;
                [savePhotos addObject:obj];
            }
        }];
    }
    if (savePhotos.count < 1) return;
    
    NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    if ([NSKeyedArchiver archiveRootObject:savePhotos toFile:[doc stringByAppendingPathComponent:SavedPhotoName]]) {
        if (doneBlock) {
            doneBlock();
        }
    }
}

- (void)cancelChecked {
    for (NSArray<XPhoto *> *photos in self.collAssets.allValues) {
        [photos enumerateObjectsUsingBlock:^(XPhoto * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.checked = NO;
        }];
    }
}

- (void)loadAssets:(PHAssetCollection *)coll {
    PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:coll options:nil];
    NSMutableArray *mArr = [NSMutableArray array];
    for (NSInteger j = 0; j < assets.count; j++) {
        XPhoto *photo = [[XPhoto alloc] init];
        PHAsset *asset = [assets objectAtIndex:j];
        photo.asset = asset;
        [mArr addObject:photo];
    }
    [self.collAssets setObject:mArr forKey:coll];
}

- (NSArray<XPhoto *> *)assetsInColl:(PHAssetCollection *)coll {
    return [self.collAssets objectForKey:coll];
}

- (XPhoto *)assetAtIndex:(NSUInteger)index {
    NSInteger searchIndex = index;
    for (PHAssetCollection *coll in self.colls) {
        NSArray<XPhoto *> * assets = [self assetsInColl:coll];
        if (searchIndex < assets.count) {
            return [assets objectAtIndex:searchIndex];
        }
        searchIndex -= assets.count;
    }
    
    return nil;
}

- (NSUInteger)indexForIndexPath:(NSIndexPath *)indexPath {
    NSUInteger index = 0;
    for (NSInteger i = 0; i < indexPath.section; i++) {
        index += [self.collAssets objectForKey:[self.colls objectAtIndex:i]].count;
    }
    index += indexPath.row;
    return index;
}

- (NSIndexPath *)indexPathForIndex:(NSUInteger)index {
    NSInteger section = 0;
    NSInteger row = index;
    for (; section < self.colls.count; section++) {
        PHAssetCollection *c = [self.colls objectAtIndex:section];
        NSArray *assets = [self.collAssets objectForKey:c];
        if (row < assets.count) {
            break;
        }
        
        row -= assets.count;
    }
    return [NSIndexPath indexPathForRow:row inSection:section];
}

#pragma mark - Get&Set
- (NSUInteger)totalCount {
    NSUInteger count = 0;
    for (NSArray *assetArr in self.collAssets.allValues) {
        count += assetArr.count;
    }
    return count;
}

- (PHFetchResult<PHAssetCollection *> *)colls {
    return self.collections;
}

- (NSMutableDictionary<PHAssetCollection *,NSMutableArray<XPhoto *> *> *)collAssets {
    if (!_collAssets) {
        _collAssets = [NSMutableDictionary dictionary];
    }
    return _collAssets;
}

@end
